package com.itqian.controller.system;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.itqian.common.exception.Assert;
import com.itqian.common.exception.EorderException;
import com.itqian.common.exception.ResponseEnum;
import com.itqian.common.utils.ResultVOUtil;
import com.itqian.common.vo.ResultVO;
import com.itqian.seller.dto.AmountBarDTO;
import com.itqian.seller.dto.AmountLineDTO;
import com.itqian.seller.dto.BarDTO;
import com.itqian.seller.dto.OrderLineDTO;
import com.itqian.seller.entity.OrderMaster;
import com.itqian.seller.mapper.OrderMasterMapper;
import com.itqian.seller.service.OrderMasterService;
import com.itqian.seller.vo.OrderExcelVO;
import com.itqian.system.entity.Constants;
import org.apache.poi.ss.usermodel.DateUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author shishuqian
 * date 2022/3/28
 * time 18:50
 **/
@RestController
@RequestMapping("/admin/order")
public class AdminOrderController {

    @Autowired
    private OrderMasterService orderMasterService;

    @Autowired
    private OrderMasterMapper orderMasterMapper;

    @GetMapping("/list/{page}/{size}")
    public ResultVO list(@PathVariable Integer page,@PathVariable Integer size){
        //参数非空校验
        Assert.notNull(page, ResponseEnum.PAGE_NOTNULL);
        Assert.notNull(size,ResponseEnum.SIZE_NOTNULL);

        Map<String, Object> map = orderMasterService.list(null, page, size);
        return ResultVOUtil.success(map);
    }


    /**
     *
     * @author shishuqian
     * @desc   根据关键字和关键字类型进行模糊查询
     *  根据订单号，买家名，手机号等
     */
    @GetMapping("/like/{type}/{keyword}/{page}/{size}")
    public ResultVO like(@PathVariable String type,
                         @PathVariable String keyword,
                         @PathVariable Integer page,
                         @PathVariable Integer size){
        //校验是否支持此类型的查询
        Assert.notBlank(type,ResponseEnum.TYPE_NOTNULL);
        String[] as = new String[]{"order_id","buyer_name","buyer_phone"};
        List<String> list = Arrays.asList(as);
        if (!list.contains(type)){
            throw new EorderException("不支持此类型的查询...");
        }
        //参数非空校验,合法性校验
        Assert.notBlank(keyword,ResponseEnum.KEYWORD_NOTNULL);
        Assert.notNull(page, ResponseEnum.PAGE_NOTNULL);
        Assert.notNull(size,ResponseEnum.SIZE_NOTNULL);

        Map<String, Object> map = orderMasterService.like(null, page, size, type, keyword);
        return ResultVOUtil.success(map);
    }

    /**
     *
     * @author shishuqian
     * @desc   商家根据订单id删除订单(并不是真正删除，而是将seller_deleted置为true)
     */

    //string -> int
    @DeleteMapping("/delete/{orderId}")
    public ResultVO delete(@PathVariable Integer orderId){
        //参数非空校验
        Assert.notNull(orderId,ResponseEnum.PARAM_NOTNULL);
        boolean b = orderMasterService.adminDelete(orderId);
        if (!b){
            return ResultVOUtil.fail("删除订单失败，请重试...");
        }
        return ResultVOUtil.success(null);
    }


    /**
     *
     *  统计所有店铺几天内的销售额折线图
     */
    @GetMapping("/amountLine/{days}")
    public ResultVO line(@PathVariable Integer days){
        //参数校验
        Assert.notNull(days,ResponseEnum.PARAM_NOTNULL);
        if (days<1 || days> Constants.STATISTICS_NUM){
            throw new EorderException("参数异常，统计天数超过规定...");
        }

        List<AmountLineDTO> amountLine = orderMasterMapper.getAmountLine(days, null);
        return ResultVOUtil.success(amountLine);
    }

    /**
     *
     *  统计该店铺几天内的销售量折线图，最多1个月
     */
    @GetMapping("/orderLine/{days}")
    public ResultVO orderLine(@PathVariable Integer days){
        //参数校验
        Assert.notNull(days,ResponseEnum.PARAM_NOTNULL);
        if (days<1 || days>Constants.STATISTICS_NUM){
            throw new EorderException("参数异常，统计天数超过规定...");
        }

        List<OrderLineDTO> orderLine = orderMasterMapper.getOrderLine(days, null);
        return ResultVOUtil.success(orderLine);
    }

    /**
     *  统计校内所有店铺成交额的柱状图(总订单数)
     */
    @GetMapping("/amountBar")
    public ResultVO amountBar(){
        List<AmountBarDTO> amountBar = orderMasterMapper.getAmountBar();
        return ResultVOUtil.success(amountBar);
    }

    /**
     *  统计校内所有店铺成交量的柱状图
     */
    @GetMapping("/orderBar")
    public ResultVO orderBar(){
        List<BarDTO> orderBar = orderMasterMapper.getOrderBar();
        return ResultVOUtil.success(orderBar);
    }

    /**
     *  导出订单信息excel
     */
    @GetMapping("/export/{days}")
    public ResultVO export(HttpServletResponse response,@PathVariable Integer days) throws IOException {
        List<OrderExcelVO> voList = new ArrayList<>();
        List<OrderMaster> list = null;
        if (days != 0){
            //查询几天内的订单
            list = orderMasterMapper.getList(days);
        }else {
            //查询所有订单
            list = orderMasterService.list();
        }
        //easyExcel要装换的实体类
        for (OrderMaster orderMaster : list) {
            OrderExcelVO vo = new OrderExcelVO();
            BeanUtils.copyProperties(orderMaster,vo);
            voList.add(vo);
        }
        //attachment指定独立文件下载  不指定则回浏览器中直接打开
        String id = UUID.randomUUID().toString().replaceAll("_","").substring(0,8);
        String fileName = "orderList_" + id + ".xlsx";
        response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        //导出excel
        EasyExcel.write(response.getOutputStream(), OrderExcelVO.class)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("order")
                .doWrite(voList);

        return ResultVOUtil.success(null);
    }


}
